import { useEffect, useState, useRef, Fragment, useCallback, useMemo } from 'react'
import { useNavigate } from 'react-router-dom'
import {
  Button,
  Table,
  Switch,
  Space,
  Tooltip,
  Modal,
  message,
} from 'antd'
import { DeleteOutlined, FormOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import UserForm from '@/components/User-manage/UserForm'
import { http } from '@/utils/http'
const { confirm } = Modal;

export default function UserList() {
  const navigate = useNavigate()
  const [userList, setUserList] = useState([])  // 用户列表数据
  const [regionList, setRegionList] = useState([])  // 区域列表数据
  const [isModalVisible, setIsModalVisible] = useState(false)  // 控制 addModal的显示与隐藏
  const [confirmLoading, setConfirmLoading] = useState(false)  // 控制 addModal确定按钮的Loading
  const [isTableLoading, setIsTableLoading] = useState(false) // 控制 Table表格是否处于Loading
  const [isSwitchLoading, setIsSwitchLoading] = useState(false)  // 控制Switch开关是否处于Loading
  const [isUpdateVisible, setIsUpdateVisible] = useState(false)  // 控制 updateModal的显示与隐藏
  const [updateID, setUpdateID] = useState(0)  // 存储需要更新的用户ID

  // 从token中获取到当前用户对应的 角色ID
  const { roleId, username, region } = JSON.parse(window.sessionStorage.getItem('news'))

  const roleObj = useMemo(() => {
    return {
      "1": "superadmin",
      "2": "admin",
      "3": "editor"
    }
  }, [])

  // 获取用户列表
  const getUserList = useCallback(async () => {
    const { data } = await http.get('/users?_expand=role')
    // console.log(data)
    setUserList(roleObj[roleId] === "superadmin" ? data : [  // 区域管理员
      ...data.filter(item => item.username === username),
      ...data.filter(item => item.region === region && roleObj[item.roleId] === "editor")
    ])
  }, [roleId, username, region, roleObj])

  // 获取区域列表
  const getRegionList = async () => {
    const { data } = await http.get('/regions')
    setRegionList(data)
  }

  useEffect(() => {
    getUserList()
    getRegionList()
  }, [getUserList])

  // 点击Switch开关的回调
  const onClickSwitch = item => {
    setIsSwitchLoading(true)
    item.roleState = !item.roleState
    setUserList([...userList])
    http.patch(`/users/${item.id}`, {
      roleState: item.roleState
    })
      .then(() => {
        setIsSwitchLoading(false)
        message.success('更新用户状态成功！', 2)
      })
      .catch(() => {
        message.error('更新用户状态失败！', 2)
        setTimeout(() => {
          setIsSwitchLoading(false)
          navigate(0)
        }, 1500)
      })
  }

  // addModal点击确定的回调
  const addModalOk = () => {
    setConfirmLoading(true)
    addForm.current.validateFields()
      .then(value => {
        // post到后端，生成ID后再重新调用get请求接口获取用户数据
        http.post('/users', {
          "username": value.username,
          "password": value.password,
          "roleState": true,
          "default": false,
          "region": value.region,
          "roleId": value.roleId
        }).then(() => {
          setIsModalVisible(false)  // 关闭 Modal
          setConfirmLoading(false)  // 确定按钮解除 loading
          getUserList()  // 重新获取 userList
          addForm.current.resetFields()  // 重置表单
          message.success('添加用户成功！', 2)
        }, () => {
          message.error('添加用户失败！', 2)
        })
      }).catch(() => message.error('请检查表单项！', 2))
  }

  // 删除用户按钮
  const deleteUser = item => {
    setIsTableLoading(true)
    confirm({
      title: `确定要删除用户${item.username}吗？`,
      icon: <ExclamationCircleOutlined />,

      onOk() {
        http.delete(`/users/${item.id}`)
          .then(() => {
            setUserList(userList.filter(data => data.id !== item.id))
            setIsTableLoading(false)
            message.success(`删除用户${item.username}成功！`, 2)
          })
          .catch(() => {
            message.error(`删除用户${item.username}失败！`, 2)
            setTimeout(() => {
              setIsTableLoading(false)
              navigate(0)
            }, 1500)
          })
      },

      onCancel() {
        setIsTableLoading(false)
        message.info('似乎什么也没有发生...', 2)
      },
    });
  }

  // 更新用户按钮
  const updateUser = item => {
    setUpdateID(item.id)
    setIsTableLoading(true)
    // 由于onCancel中设置关闭 Modal后setIsDisabled为不禁用
    // 于是这里需要判断，点击更新用户按钮时，若更新的用户是“超级管理员”，则需要重新setIsDisabled为禁用
    if (item.roleId === 1) setIsDisabled(true)
    setIsUpdateVisible(true)
    // 把setFieldsValue包裹成异步，确保状态更新完毕之后，再去拿到updateForm表单实例去调用setFieldsValue
    setTimeout(() => {
      updateForm.current.setFieldsValue({
        username: item.username,
        password: item.password,
        region: item.region,
        roleId: item.roleId
      })
    }, 10)
  }

  // updateModal点击确定按钮的回调
  const updateModalOk = () => {
    updateForm.current.validateFields()
      .then(value => {
        http.patch(`/users/${updateID}`, {
          "username": value.username,
          "password": value.password,
          "region": value.region,
          "roleId": value.roleId
        }).then(() => {
          setIsUpdateVisible(false)  // 关闭 Modal
          setIsTableLoading(false)  // Table处于不loading
          getUserList()  // 重新获取 userList
          updateForm.current.resetFields()  // 重置表单
          message.success('更新用户成功！', 2)
        }, () => {
          message.error('更新用户失败！', 2)
        })
      }).catch(() => {
        message.error('请检查表单项！', 2)
      })
  }

  // Table表格列
  const columns = [
    {
      title: '区域',
      align: 'center',
      dataIndex: 'region',
      filters: [
        {
          text: '全球',
          value: ''
        },
        ...regionList.map(item => ({
          text: item.title,
          value: item.value
        }))
      ],
      onFilter: (value, record) => record.region === value,
      render: region => {
        return <b>{region === '' ? '全球' : region}</b>
      }
    },
    {
      title: '角色名称',
      align: 'center',
      dataIndex: 'role',
      render: role => role?.roleName
    },
    {
      title: '用户名',
      align: 'center',
      dataIndex: 'username'
    },
    {
      title: '用户状态',
      align: 'center',
      render: item => {
        return <Switch
          checkedChildren="开启"
          unCheckedChildren="关闭"
          disabled={item.default}
          checked={item.roleState}
          onClick={() => { onClickSwitch(item) }}
          loading={isSwitchLoading}
        />
      }
    },
    {
      title: '操作',
      align: 'center',
      render: item => {
        return (
          <Space>
            <Tooltip title="delete" placement="left">
              <Button danger type="primary" shape="circle" icon={<DeleteOutlined />}
                disabled={item.default} onClick={() => deleteUser(item)} />
            </Tooltip>
            <Tooltip title="edit" placement="right">
              <Button type="primary" shape="circle" icon={<FormOutlined />}
                disabled={item.default} onClick={() => updateUser(item)} />
            </Tooltip>
          </Space>
        )
      }
    }
  ]

  const addForm = useRef(null)  // 创建 添加用户 表单实例
  const [isDisabled, setIsDisabled] = useState(false)  // 是否禁用区域框

  const updateForm = useRef(null)  // 创建 更新用户 表单实例

  return (
    <Fragment>
      <Button type='primary' style={{ margin: '10px 0px' }} onClick={() => {
        setIsModalVisible(true)
        setConfirmLoading(false)
      }}>添加用户</Button>
      <Table
        dataSource={userList}
        columns={columns}
        rowKey={item => item.id}
        pagination={{
          pageSize: 5
        }}
        loading={isTableLoading}
      />
      {/* 添加用户弹出框 */}
      <Modal
        visible={isModalVisible}
        title="添加用户"
        okText="Create"
        onCancel={() => {
          setIsModalVisible(false)
          addForm.current.resetFields()
          setIsDisabled(false)
          message.info('似乎什么也没有发生...', 2)
        }}
        onOk={addModalOk}
        confirmLoading={confirmLoading}
      >
        <UserForm ref={addForm} isDisabled={isDisabled} setIsDisabled={setIsDisabled} />
      </Modal>
      {/* 更新用户弹出框 */}
      <Modal
        destroyOnClose
        visible={isUpdateVisible}
        title="更新用户"
        okText="Update"
        onCancel={() => {
          setIsUpdateVisible(false)
          updateForm.current.resetFields()
          setIsDisabled(false)
          setIsTableLoading(false)
          message.info('似乎什么也没有发生...', 2)
        }}
        onOk={updateModalOk}
      >
        <UserForm isUpdate={true} ref={updateForm} isDisabled={isDisabled} setIsDisabled={setIsDisabled} />
      </Modal>
    </Fragment>
  )
}